package com.example.roomdatabasetest;

import android.content.Context;

import androidx.room.Room;

import java.util.ArrayList;
import java.util.List;

/*
    因为数据库操作开销比较大，所以采用的是单例模式进行实现
 */
public class CarMode implements ICarMode {
    private  static volatile CarMode carMode;// 通过单例进行操作
    private CarDataBase carDataBase;
    private CarDao carDao;
    // 创建数据库
    private CarMode(Context context){
        carDataBase = Room.databaseBuilder(context,CarDataBase.class,"car.db").
                allowMainThreadQueries().build();
        carDao = carDataBase.getCarDao();

    }
    // 获取单例
    public static CarMode getInstance(Context context){
        if(carMode == null){
            synchronized (CarMode.class){
                if(carMode == null)
                carMode = new CarMode(context);
            }
        }
        return carMode;
    }
    @Override
    public void addItem(Car car) {
        carDao.insertCar(car);
    }

    @Override
    public void deleteItem(Car car) {
        carDao.deleteCar(car);
    }

    @Override
    public List<Car> queryAll() {
        return carDao.queryAllCars();
    }

    @Override
    public void updateItem(Car car) {
        carDao.updateCars(car);
    }
}
